package com.gitee.frank.minispring.config.parse;

import com.gitee.frank.minispring.beans.Bean;
import com.gitee.frank.minispring.config.Property;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;


/**
 * Description:
 *
 * @author: Frank
 * @date: 2018/3/13
 */
public class ConfigManager {

    /**
     * @param contextPath
     * @return
     */
    public static Map<String, Bean> getConfig(String contextPath) {
        Map<String, Bean> map = new HashMap<>();
        SAXReader reader = new SAXReader();
        InputStream in = ConfigManager.class.getResourceAsStream(contextPath);
        Document doc;
        try {
            doc = reader.read(in);
        } catch (DocumentException e) {
            e.printStackTrace();
            throw new RuntimeException("读取配置失败，请检查xml配置！");
        }
        String Xpath = "//bean";
        List<Element> beans = doc.selectNodes(Xpath);
        if (beans != null) {
            for (Element beanEle : beans) {
                Bean bean = new Bean();
                String id = beanEle.attributeValue("id");
                String className = beanEle.attributeValue("class");
                String scope = beanEle.attributeValue("scope");

                if (Stringu != null) {
                    bean.setScope(scope);
                }
                bean.setClassName(className);
                bean.setId(id);

                List<Element> properties = beanEle.elements("property");
                if (properties != null) {
                    for (Element el : properties) {
                        Property property = new Property();
                        String pName = el.attributeValue("name");
                        String pValue = el.attributeValue("value");
                        String pRef = el.attributeValue("ref");
                        property.setName(pName);
                        property.setValue(pValue);
                        property.setRef(pRef);
                        bean.getProperties().add(property);
                    }
                }
                map.put(id, bean);
            }
        }
        Set<Entry<String, Bean>> entrySet = map.entrySet();
        for (Entry<String, Bean> entry : entrySet) {
            List<Property> properties = entry.getValue().getProperties();
            for (Property property : properties) {
                String ref = property.getRef();
                if (ref != null && !map.containsKey(ref)) {
                    throw new RuntimeException("非法参数：" + property.getRef());
                }
            }
        }
        return map;
    }
}